<template>
	<view :style="objColor">
		<!-- homeSub/pages/startCharging/startCharging.wxml -->
		<!-- 启动充电 -->
		<!-- v-if="waitingDisplay" -->
		<view>

			<!-- <view class="content" style="height: 750rpx">
                <l-svga src="https://oos-cn.ctyunapi.cn/front-end/static/homeSub/images/out.svga"></l-svga>
            </view> -->
			<image class="header-image" src="https://oos-cn.ctyunapi.cn/front-end/static/homeSub/images/startChargingBg.png"
				style="width: 100%"></image>
			<!-- <view class="main_time">{{ waitingTime }}正在启动中</view> -->
			<view style="width: 100vw; height:353rpx;padding-top: 130rpx;overflow: hidden;" id="chargingCanvas">
				<l-svga ref="svga"></l-svga>
			</view>
			<!-- <div class="svgaPage">
                <div id="chargingCanvas"></div>
            </div> -->
			<view class="starting">请耐心等待，正在努力安全启动中</view>
			<view class="w_text">
				<view>
					<view class="t_sign">
						<view class="t_signShadow">小提示</view>
					</view>
				</view>
				<view class="t_tips">
					<text>1、请保持在当前页面等待充电启动结果，否则可能会启动失败；</text>
					<text>2、启动过程中请勿拔枪，拔枪可能会造成充电异常，并可能发生安全风险；</text>
					<text>3、为了您的安全，充电过程中请勿停留在车内；</text>
					<text>4、充电结束后有1分钟的等待支付时长，如有需要选择优惠方式，可在此期间内自行选择，否则1分钟后系统取最优方案进行结算；</text>
				</view>
			</view>
		</view>
		<!-- 
        <view class="overtime" v-if="!waitingDisplay">
            <image class="img" src="https://oos-cn.ctyunapi.cn/front-end/static/homeSub/images/overtime.png"></image>
            <view class="overtimeTitle">
                <view>充电启动失败，请重新启动充电！</view>
                <view v-show="failureReason">{{ failureReason }}</view>
            </view>
 
            <button class="againButton" type="primary" @tap="again">重新启动</button>
        </view> -->

		<uni-popup ref="showBulletFrame" safe-area type="center" :mask-click="false">
			<view class="BulletFrameCon">
				<view class="bulletTitle">
					启动失败
					<image class="img" src="https://oos-cn.ctyunapi.cn/front-end/static/homeSub/images/delete2.png" @tap="again">
					</image>
				</view>
				<view class="bulletVal">
					<view>充电启动失败，请重新启动充电！</view>
					<view>({{ failureReason }})</view>
				</view>
				<view class="bulletButton" @tap="again">
					重新启动
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	'use strict';
	//import SVGA from "svgaplayerweb";
	import {
		cancelOrder
	} from '@/api/zhifufen'
	var https_1 = require('../../../api/https.js');
	var newapp = getApp()
	// var parser = new Parser();
	// var player = new Player();
	// var parser2 = new Parser();
	// var player2 = new Player();
	// var parser3 = new Parser();
	// var player3 = new Player();
	var videoItem2 = '';
	var videoItem3 = '';
	var waitingTimes = '';
	var getnum = 0;
	var st = null;
	var times = '';
	export default {
		data() {
			return {
				stationId: '',
				waitingTime: 180,
				waitingDisplay: true,
				animation: 0,
				parameter: {},
				busId: '',
				gunNo: '',
				pileNo: '',
				player: {},
				parser: {},
				failureReason: '启动超时', // 失败原因
			};
		}
		/**
		 * 生命周期函数--监听页面加载
		 */
		,
		onLoad: function(options) {
			this.stationId = options.stationId
			uni.showLoading({
				title: '加载中'
			});
			let parameter = decodeURIComponent(options.parameter)
			parameter = JSON.parse(options.parameter)
			parameter.qrCode = decodeURIComponent(parameter.qrCode)
			this.setData({
				parameter
			})
			this.$nextTick(() => {
				setTimeout(() => {
					this.getMove()
				}, 200)
			})

		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		// onShow: function () {},
		/**
		 * 生命周期函数--监听页面隐藏
		 */
		// onHide: function () {},
		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function () {
            console.log('-----onUnload------');
		    clearInterval(waitingTimes);
		    clearInterval(times);
		},
		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {},
		mounted() {
			// 动态引入类库
			// 　　　　const script = document.createElement('script')
			// 　　　　script.src = SVGA
			// 　　　　document.head.appendChild(script)
			// 　　　　script.onload = this.ready()
		},
		methods: {
			moveHandle: function() {
				return false
			},
			//充电鉴权
			authentication: function() {
				var that = this;
				if (this.parameter.disposablePayMode) {
					https_1.disposableStartCharge(this.parameter).then(function(res) {
						if (res.code == 0) {
							that.busId = res.data.busId,
								that.gunNo = res.data.gunNo,
								that.pileNo = res.data.pileNo
							times = setInterval(function() {
								that.chkCharge(res.data.busId, res.data.gunNo, res.data.pileNo);
							}, 3000);
						} else {
							clearInterval(waitingTimes);
							clearInterval(times); //this.out()

							// 弹出失败提示框
							that.waitingDisplay = true
							that.$refs.showBulletFrame.open()
							that.failureReason = res.msg
						}
					});
				} else if (this.parameter.isZhiFuFen) {
					// 支付分支付
					https_1.disposableStartCharge(this.parameter).then(function(res) {
						if (res.code == 0) {
							that.busId = res.data.busId,
								that.gunNo = res.data.gunNo,
								that.pileNo = res.data.pileNo
							times = setInterval(function() {
								that.chkCharge(res.data.busId, res.data.gunNo, res.data.pileNo);
							}, 3000);
						} else {
							clearInterval(waitingTimes);
							clearInterval(times); //this.out()

							// 弹出失败提示框
							that.waitingDisplay = true
							that.$refs.showBulletFrame.open()
							that.failureReason = res.msg
							that.zhifufenCancelOrder(`支付分取消订单：充电接口disposableStartCharge code：${res.code}`)
						}
					});
				} else {
					https_1.startCharge(this.parameter).then(function(res) {
						if (res.code == 0) {

							that.busId = res.data.busId,
								that.gunNo = res.data.gunNo,
								that.pileNo = res.data.pileNo
							times = setInterval(function() {
								that.chkCharge(res.data.busId, res.data.pileNo, res.data.gunNo);
							}, 3000);
						} else {
							clearInterval(waitingTimes);
							clearInterval(times); //this.out()

							// 弹出失败提示框
							that.waitingDisplay = true
							that.$refs.showBulletFrame.open()
							that.failureReason = res.msg

							// uni.showModal({
							//     title: '信息提示',
							//     content: res.msg,
							//     showCancel: false,
							//     success: function (res) {
							//         if (!res.cancel) {
							//             uni.navigateBack();
							//         }
							//     }
							// });



						} // else{
						//   wx.navigateTo({
						//     url: `/homeSub/pages/terminal/gunDetail/gunDetail?pileNo=${this.data.parameter.pileNo}&gunNo=${this.data.parameter.gunNo}`
						//  })
						// }
					});
				}
			},

			// 重新启动
			unFrozenAccount: function() {
				var that = this;
				let busId = this.busId

				if (busId == 'undefined' || busId == undefined) {
					busId = null
				}
				https_1
					.unFrozenAccount({
						busId
					})
					.then(function(res) {
						if (res.code == 0) {
							that.busId = res.data.busId,
								that.gunNo = res.data.gunNo,
								that.pileNo = res.data.pileNo
							// times = setInterval(function () {
							//     that.chkCharge(res.data.busId, res.data.gunNo, res.data.pileNo);
							// }, 3000);
						} else {
							clearInterval(waitingTimes);
							clearInterval(times); //this.out()

							// 弹出失败提示框
							// that.waitingDisplay=true
							// that.$refs.showBulletFrame.open()
							// that.failureReason = res.msg

							// uni.showModal({
							//     title: '信息提示',
							//     content: res.msg,
							//     showCancel: false,
							//     success: function (res) {
							//         if (!res.cancel) {
							//             uni.navigateBack();
							//         }
							//     }
							// });
						}
					});
			},

			// 充电启动倒数
			goCharge: function() {
				var that = this;

				waitingTimes = setInterval(function() {
					if (that.waitingTime <= 1) {
						that.failureReason = '启动超时'
						clearInterval(waitingTimes);
						clearInterval(times); //this.out()

						that.waitingDisplay = false
						that.$refs.showBulletFrame.open()
						that.unFrozenAccount()
					}

					that.waitingTime = --that.waitingTime
				}, 1000);
			},

			// 获取动图svga 开启动画
			getMove() {
				let that = this
				this.$refs.svga.render(async (parser, player) => {
					// 加载动画报错处理重新执行动画
					try {
						//#ifdef APP-PLUS || MP-WEIXIN
						var videoItem = ''
						if(newapp.globalData.sellerNo == 'hyc'){
							videoItem = await parser.load(
							`${newapp.globalData.imgUrl}/h5/cartoon/mobilization3.svga`);
							videoItem2 = await parser.load(
								`${newapp.globalData.imgUrl}/h5/cartoon/quiet3.svga`);
							videoItem3 = await parser.load(
								`${newapp.globalData.imgUrl}/h5/cartoon/out3.svga`);
						}else{
							videoItem = await parser.load(
							"https://oos-cn.ctyunapi.cn/front-end/static/cartoon/mobilization3.svga");
							videoItem2 = await parser.load(
								"https://oos-cn.ctyunapi.cn/front-end/static/cartoon/quiet3.svga");
							videoItem3 = await parser.load(
								"https://oos-cn.ctyunapi.cn/front-end/static/cartoon/out3.svga");
						}

						
						//#endif
						//#ifdef H5
						var videoItem = await parser.load(
							`${newapp.globalData.imgUrl}/h5/cartoon/mobilization3.svga`);
						videoItem2 = await parser.load(
							`${newapp.globalData.imgUrl}/h5/cartoon/quiet3.svga`);
						videoItem3 = await parser.load(
							`${newapp.globalData.imgUrl}/h5/cartoon/out3.svga`);
						//#endif
						uni.hideLoading();
						await player.setVideoItem(videoItem);
						player.loops = 1
						player.startAnimation()
						
						let status = false
						
						uni.showLoading({
							title: '动画加载启动中'
						});
	
						setTimeout(()=>{
							if(status) return
							console.log('走到这里了吗setTimeout')
							status = true
							uni.hideLoading();
							player.stopAnimation()
							console.log('走到这里了吗setTimeout1')
							that.enter()
							console.log('走到这里了吗setTimeout2')
						},2000)
	
						// 监听动画完成
						player.onFinished(() => {
							console.log('走到这里了吗')
							if(status) return
							console.log('走到这里了吗1')
							status = true
							uni.hideLoading();
							player.stopAnimation()
							that.enter()
							console.log('走到这里了吗2')
						})
						
						this.goCharge()
						this.authentication()
					} catch (err) {
						console.log(err, '动画报错信息')
						that.refreshPage()
					}
				})
			},
			refreshPage() {
				let that = this
				uni.hideLoading();
				that.zhifufenCancelOrder('启动动画加载失败')
				uni.showModal({
					title: '提示',
					content: '启动动画加载失败，请重新加载。',
					showCancel: false,
					confirmText: '返回',
					success(res) {
						if (res.confirm) {
							let parameter = JSON.stringify(that.parameter)
							// uni.redirectTo({
							// 	url: `/homeSub/pages/startCharging/startCharging?parameter=${parameter}`
							// })
							uni.navigateBack()
						}
					},
				})
			},
			// 静止动画
			// 静止动画
			enter: function() {
				this.$refs.svga.render(async (parser, player2) => {
					console.log(videoItem2,'dosajfkdlsjafkld')
					await player2.setVideoItem(videoItem2);

					// 设置当前动画的循环次数，0代表无限循环 默认 0
					player2.loops = 999
					// 开始播放动画，reverse = true 时则反向播放。
					player2.startAnimation()
				})

			},
			toPowerPage(){
				// #ifdef MP-WEIXIN
				//解决内存不足跳转
				uni.reLaunch({
					url: `/echartsPages/pages/power/power?busId=${this.busId}&pileNo=${this.pileNo}&gunNo=${this.gunNo}&backType=2` +
						'&stationId=' + this.stationId
				});
				// #endif
				
				// #ifndef MP-WEIXIN
				uni.redirectTo({
					url: `/echartsPages/pages/power/power?busId=${this.busId}&pileNo=${this.pileNo}&gunNo=${this.gunNo}&backType=2` +
						'&stationId=' + this.stationId
				});
				// #endif
			},
			// 退出动画
			out: function() {
				this.$refs.svga.render(async (parser, player) => {
					try{
						await player.setVideoItem(videoItem3);
						// 设置当前动画的循环次数，0代表无限循环 默认 0
						player.loops = 1
						// 开始播放动画，reverse = true 时则反向播放。
						player.startAnimation()
						//player.onPercentage(this.enter)
						// 监听动画完成
						let status = false
						
						
						player.onFinished(() => {
							if(status) return
							status = true
							player.stopAnimation(true)
							player.clearDynamicObjects && player.clearDynamicObjects()
							console.log('动画结束333')
							this.toPowerPage()
						})
						
						// 添加定时器防止onFinished回调没走到
						setTimeout(()=>{
							if(status) return
							status = true
							this.toPowerPage()
						},2000)
					}catch(e){
						console.log('执行动画报错，强行跳转')
						this.toPowerPage()
					}
				})
			},

			// 跳转到充电详情
			retreat: function(a) {
				if (a === 1) {
					// uni.redirectTo({
					//     url: '/echartsPages/pages/power/power?busId=' + this.busId + '&pileNo=' + this.pileNo + '&gunNo=' + this.gunNo + '&backType=2'
					// });
					//解决内存不足跳转
					// #ifdef MP-WEIXIN
					uni.reLaunch({
						url: '/echartsPages/pages/power/power?busId=' + this.busId + '&pileNo=' + this.pileNo + '&gunNo=' +
							this.gunNo + '&backType=2' + '&stationId=' + this.stationId
					});
					// #endif

					// #ifndef MP-WEIXIN
					uni.redirectTo({
						url: '/echartsPages/pages/power/power?busId=' + this.busId + '&pileNo=' + this.pileNo + '&gunNo=' +
							this.gunNo + '&backType=2' + '&stationId=' + this.stationId
					});
					// #endif

				}
			},

			// 重新启动  返回上一页
			again: function() {
				this.unFrozenAccount()
				console.log('进入')
				uni.navigateBack();
				this.$refs.showBulletFrame.close()
				// this.waitingTime=120,
				//     this.waitingDisplay=true
				// this.getMove();
				// this.authentication()
			},

			/**
			 * 轮询检测充电
			 */
			chkCharge: function(busId, pileNo, gunNo) {
				var that = this;
				var data = {
					busId: busId,
					pileNo: pileNo,
					gunNo: gunNo
				};
				https_1.queryIsChargeByBusId(data).then(function(res) {
					if (res.code == 0) {
						console.log('轮询成功11')
						//获取所有充电订单
						// $this.getbillNo(busId,gunNo,pileNo)
						clearInterval(waitingTimes);
						clearInterval(times);
						that.out();
					} else if (res.code == 3) {
						if (that.waitingTime < 1) {
							that.failureReason = '启动超时'
							clearInterval(waitingTimes);
							clearInterval(times);
							that.waitingDisplay = false
							that.$refs.showBulletFrame.open()
							that.zhifufenCancelOrder('支付分取消订单：充电接口queryIsChargeByBusId code：3')
						}
					} else if (res.code == 500) {
						that.failureReason = '启动充电报错'
						clearInterval(waitingTimes);
						clearInterval(times);
						that.waitingDisplay = false
						that.$refs.showBulletFrame.open()
						that.zhifufenCancelOrder('支付分取消订单：充电接口queryIsChargeByBusId code：500')
					}
				});
			},

			/**
			 * 弹框
			 */
			wxalert: function(str) {
				uni.showModal({
					title: '消息提示',
					content: str,
					showCancel: false
				});
			},
			// 微信支付分取消订单
			zhifufenCancelOrder(str) {
				console.log(str)
				let that = this
				if (that.parameter.isZhiFuFen) {
					cancelOrder({
						"sellerId": getApp().globalData.sellerId,
						"busId": that.parameter.orderNumber,
						"cancelReason": str
					}).then(res => {
						console.log(res, '支付分取消订单')
						let tips = res.code == 0 ? '支付分取消订单成功' : `支付分取消失败请联系客服手动取消busId:${busId}`
						uni.showModal({
							title: '提示',
							content: tips,
							success: function(res) {
								// uni.navigateBack()
							}
						});
					})
				}
			}
		}
	};
</script>
<style lang="less">
	/* homeSub/pages/startCharging/startCharging.wxss */
	@import "../../../commin/commin.less";

	.w_text {
		width: 656rpx;
		position: fixed;
		bottom: 30rpx;
		left: 0;
		right: 0;
		margin: 0 auto;
		color: #34F0B9;
		z-index: 2;
		background-color: transparent;
		backdrop-filter: blur(3px); //毛玻璃属性
		border: 1rpx solid #34F0B9;
		border-radius: 10rpx;
		padding: 20rpx 0;

		.t_sign {
			font-size: 28rpx;
			text-align: center;
		}

		.t_tips {
			padding: 30rpx;
			font-size: 24rpx;

			text {
				display: block;
				margin-top: 20rpx;
				text-indent: 40rpx;
				line-height: 45rpx;
			}
		}
	}

	.header-image {
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 100%;
	}

	.coverView {
		position: fixed;
		top: 0;
		width: 414px;
		z-index: 100;
		background: rgba(0, 0, 0, 0.5);
	}

	.starting {
		text-align: center;
		font-size: 24rpx;
		color: #34F0B9;
		letter-spacing: 4rpx;
		position: relative;
		z-index: 2;
	}

	.overtime {
		text-align: center;
		padding-top: 205rpx;
	}

	.overtimeTitle {
		text-align: center;
		font-size: 28rpx;
		font-weight: 500;
		color: @blue;
		letter-spacing: 4rpx;
		margin-top: 12rpx;
	}

	.againButton {
		width: 680rpx;
		height: 88rpx;
		background: @blue;
		;
		box-shadow: 0px 3px 6px 0px rgba(0, 110, 212, 0.3);
		border-radius: 44rpx;
		line-height: 88rpx;
		font-size: 32rpx;
		position: fixed;
		bottom: 144rpx;
		right: 0;
		left: 0;
	}

	.main_time {
		text-align: center;
		position: relative;
		top: 200rpx;
		color: #34F0B9;
		font-size: 27rpx;
	}

	#chargingCanvas {
		width: 256rpx;
		height: 256rpx;
		position: relative;
		left: 50%;
		transform: translateX(-50%);
	}

	.t_signShadow {
		line-height: 50rpx;
		display: inline-block;
		box-shadow: 0 7px 5px -5px #34F0B9;
	}


	.BulletFrameCon {
		width: 702rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		font-family: PingFang SC;
		overflow: hidden;

		.bulletTitle {
			padding: 45rpx 0rpx 40rpx 0rpx;
			text-align: center;
			font-size: 34rpx;
			font-weight: bold;
			color: #303133;

			.img {
				position: absolute;
				right: 23rpx;
				width: 25rpx;
				height: 25rpx;
				vertical-align: middle;
				margin-right: 9rpx;
			}
		}

		.bulletVal {
			font-size: 28rpx;
			font-weight: 500;
			color: #909399;
			line-height: 65rpx;
			padding: 0 35rpx;
			text-align: center;
		}

		.bulletButton {
			margin-top: 86rpx;
			text-align: center;
			border-top: 1rpx solid #DCDFE6;
			padding: 40rpx 0;
			font-weight: bold;
			color: var(--textColor);
			font-size: 30rpx;
		}
	}
</style>